package com.hk.core.autoconfigure.data.r2dbc;

import com.hk.core.authentication.api.reactive.ReactiveSecurityContextUtils;
import com.hk.core.autoconfigure.data.TenantIdResolverProvider;
import com.hk.core.data.r2dbc.tenants.ReactiveTenantIdResolver;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author Kevin
 * @date 2024-04-11 22:59
 */
@RequiredArgsConstructor
public final class UserPrincipalTenantIdResolver implements ReactiveTenantIdResolver {

    private final List<TenantIdResolverProvider> resolverProviders;

    @Override
    public Mono<String> resolve(String value) {
        return Flux.fromIterable(resolverProviders)
                .filter(item -> item.test(value))
                .next()
                .flatMap(resolverProvider -> ReactiveSecurityContextUtils.isAuthenticated()
                        .flatMap(authenticated -> authenticated ? ReactiveSecurityContextUtils.getPrincipal()
                                .map(principal -> resolverProvider.getProvider().apply(principal)) : Mono.empty()));
    }
}
